<?php

namespace app\common\model\Product;

use think\Model;

/**
 * 商品模型
 */
class Product extends Model{
    // 模型对应的表
    protected $table="pre_product";

    // 开启自动写入
    protected $autoWriteTimestamp=false;

    protected $createTime=false;

    protected $updateTime=false;

    protected $append=[
        'thumbs_cdn',//多张图的
        'cover_cdn',//单张图
        'flag_text',
    ];

    // 图片字段的获取器 thumbs_cdn
    public function getThumbsCdnAttr($value,$data){
        // 获取的是config.php当中的cdn选项
        $cdn=config('cdn');

        // $thumbs=empty($data['thumbs']) ? [] : explode(',',$data['thumbs']);
        $thumbs=empty($data['thumbs']) ? [] : trim($data['thumbs']);

        if(empty($thumbs)){
            return [];
        }

        // 字符串替换
        $thumbs=str_replace("uploads/",$cdn."/uploads/",$thumbs);

        // 再转换为数组
        $list=explode(',',$thumbs);

        return $list;
    }

    public function getCoverCdnAttr($value,$data){
        $cdn=config('cdn');

        $thumbs=empty($data['thumbs']) ? [] : trim($data['thumbs']);

        if(empty($thumbs)){
            return [];
        }

        $thumbs=str_replace("uploads/",$cdn."/uploads/",$thumbs);

        $list=explode(',',$thumbs);

        if(count($list) > 0){
            return $list[0];
        }else{
            return $cdn."/assets/admin/images/product.jpg";
        }
    }

    public function getFlagTextAttr($value,$data){
        $list=[''=>'未定义类型',1=>'热门',2=>'新品',3=>'推荐'];
        return $list[$data['flag']];
    }

    // 关联查询
    public function type(){
        return $this->belongsTo('app\common\model\Product\Type','typeid','id',[],'LEFT')->setEagerlyType(1);
    }
}